﻿using System.Windows.Input;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Keyboard = Microsoft.Xna.Framework.Input.Keyboard;

namespace Silverlight3dApp.Recipes.Chapter01.Lesson01
{
    public class MadnessGame : Game
    {
        private Camera _camera;

        private BasicEffect _basicEffect;
        private CoordinateCross _coordinateCross;

        private Matrix _worldTranslation = Matrix.Identity;
        private Matrix _worldRotation = Matrix.Identity;

        public MadnessGame()
        {
            Content.RootDirectory = "Content";
        }

        protected override void Initialize()
        {
            _camera = new Camera(this, new Vector3(0, 0, 10), new Vector3(0, 0, 0), Vector3.Up);
            Components.Add(_camera);
            base.Initialize();
        }

        protected override void LoadContent()
        {
            _basicEffect = new BasicEffect(GraphicsDevice);
            _coordinateCross = new CoordinateCross(GraphicsDevice);
            base.LoadContent();
        }

        protected override void Update(GameTime gameTime)
        {
            var keyState = Keyboard.GetState();
            //_worldRotation *= Matrix.CreateRotationY(MathHelper.PiOver4 / 60);
            if (keyState.IsKeyDown(Key.Left))
            {
                _worldTranslation *= Matrix.CreateTranslation(-0.01f, 0, 0);
            }
            if (keyState.IsKeyDown(Key.Right))
            {
                _worldTranslation *= Matrix.CreateTranslation(0.01f, 0, 0);
            }
            if (keyState.IsKeyDown(Key.Up))
            {
                _worldTranslation *= Matrix.CreateTranslation(0, 0.01f, 0);
            }
            if (keyState.IsKeyDown(Key.Down))
            {
                _worldTranslation *= Matrix.CreateTranslation(0, -0.01f, 0);
            }
            base.Update(gameTime);
        }

        protected override void Draw(GameTime gameTime)
        {
            if (GraphicsDevice.RasterizerState.CullMode != CullMode.None)
            {
                GraphicsDevice.RasterizerState = new RasterizerState
                                                     {
                                                         CullMode = CullMode.None
                                                     };
            }
            //GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, Colors.CornflowerBlue, 1.0f, 0);

            _basicEffect.World = _worldRotation * _worldTranslation;
            _basicEffect.View = _camera.View;
            _basicEffect.Projection = _camera.Projection;
            _basicEffect.VertexColorEnabled = true;
            foreach (var pass in _basicEffect.CurrentTechnique.Passes)
            {
                pass.Apply();
                _coordinateCross.DrawUsingPresetEffect();
            }
            base.Draw(gameTime);
        }
    }
}